import {Component, OnDestroy, OnInit} from '@angular/core';
import {MapUtil} from '../../../../util/map-util';
import {Subscription} from 'rxjs/Subscription';
import {Observable} from 'rxjs/Observable';
import {ActivatedRoute, Router} from '@angular/router';
import {MsgConstants, RoutConstants} from '../../../../constants/constants';
import {SiteRangeMapService} from './site-range-map.service';
import {ResponseUtil} from '../../../../util/response-util';
import {OneDialogService} from '../../../../widgets/one-dialog/one-dialog.service';

declare var BMap;
declare var BMapLib;
declare var INFOBOX_AT_TOP;
declare var $;

@Component({
  selector: 'app-site-range-map',
  templateUrl: './site-range-map.component.html',
  styleUrls: ['./site-range-map.component.css']
})
export class SiteRangeMapComponent implements OnInit, OnDestroy {

  map: any;
  resizeEvent: Subscription;
  lastInfo: any;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private mapUtil: MapUtil,
    private responseUtil: ResponseUtil,
    private dialogService: OneDialogService,
    private siteRangeMapService: SiteRangeMapService
  ) {}

  ngOnInit() {
    this.loadMapScript();
    this.screenChange();
  }
  ngOnDestroy () {
    this.destroyResize();
  }
  /**
   * 屏幕大小改变
   */
  screenChange() {
    this.resizeEvent = Observable.fromEvent(window, 'resize')
      .debounceTime(100) // 以免频繁处理
      .subscribe((event) => {
        // 这里处理页面变化时的操作
        $('.one-notbreadcrumb').css('height', window.innerHeight - 50 + 'px');
        $('#siteRangeMap').css('height', window.innerHeight - 50 + 'px');
      });
  }
  /**
   * 取消监听屏幕变化
   * */
  destroyResize() {
    this.resizeEvent.unsubscribe();
  }
  loadMapScript() {
    this.mapUtil.loadMapScript(() => this.initMap());
  }

  initMap () {
    $('.one-notbreadcrumb').css('height', window.innerHeight - 50 + 'px');
    $('#siteRangeMap').css('height', window.innerHeight - 50 + 'px');
    this.map = new BMap.Map('siteRangeMap', {enableMapClick: false, minZoom: 5, maxZoom: 18});
    const centerPoint = new BMap.Point(113.658221, 34.780377);  // 创建点坐标
    this.map.centerAndZoom(centerPoint, 12);
    this.map.enableScrollWheelZoom();
    // 地图样式
    const mapStyle = [
      {
        'featureType': 'land',
        'elementType': 'geometry',
        'stylers': {
          'color': '#e7f7fc'
        }
      },
      {
        'featureType': 'water',
        'elementType': 'all',
        'stylers': {
          'color': '#96b5d6'
        }
      },
      {
        'featureType': 'green',
        'elementType': 'all',
        'stylers': {
          'color': '#b0d3dd'
        }
      },
      {
        'featureType': 'highway',
        'elementType': 'geometry.stroke',
        'stylers': {
          'color': '#d1c6a6'
        }
      },
      {
        'featureType': 'highway',
        'elementType': 'geometry.fill',
        'stylers': {
          'color': '#e6d9ab'
        }
      },
      {
        'featureType': 'arterial',
        'elementType': 'geometry.fill',
        'stylers': {
          'color': '#eeeeee'
        }
      },
      {
        'featureType': 'arterial',
        'elementType': 'geometry.stroke',
        'stylers': {
          'color': '#cccccc'
        }
      },
      {
        'featureType': 'local',
        'elementType': 'geometry.fill',
        'stylers': {
          'color': '#eeeeee'
        }
      },
      {
        'featureType': 'water',
        'elementType': 'geometry.fill',
        'stylers': {
          'color': '#b6c6de'
        }
      },
      {
        'featureType': 'subway',
        'elementType': 'all',
        'stylers': {
          'visibility': 'off'
        }
      },
      {
        'featureType': 'green',
        'elementType': 'geometry.fill',
        'stylers': {
          'color': '#cddbd2'
        }
      },
      {
        'featureType': 'land',
        'elementType': 'all',
        'stylers': {
          'color': '#edf1f5'
        }
      },
      {
        'featureType': 'administrative',
        'elementType': 'geometry',
        'stylers': {
          'color': '#a7c8ec'
        }
      },
      {
        'featureType': 'railway',
        'elementType': 'all',
        'stylers': {
          'visibility': 'off'
        }
      }
    ]; // 白底
    this.map.setMapStyle({styleJson: mapStyle});
    this.mapUtil.loadMapLib('http://api.map.baidu.com/library/InfoBox/1.2/src/InfoBox_min.js');
    this.getSiteRangeInfo();
  }

  /**
   * 站点详情内容
   * @param dataObj
   * @returns {string}
   */
  siteInfoHtml = (dataObj) => {
    return `
    <div class='one-monitor-info'>
      <div class='one-monitor-info-head'>
        ${dataObj.siteName}
        <small>（${dataObj.longitude + ',' + dataObj.latitude}）</small>
      </div>
      <div class='one-monitor-info-body'>
        <ul class='list-unstyled' style='margin-top: 10px;'>
          <li class='one-warn-detail-info'>
            <ul class='list-inline'>
              <li class='one-light-text'>开始检测时间</li>
              <li style="width: 160px;">${dataObj.startDate}</li>
            </ul>
          </li>
          <li class='one-warn-detail-info'>
            <ul class='list-inline'>
              <li class='one-light-text'>结束检测时间</li>
              <li style="width: 160px;">${dataObj.endDate}</li>
            </ul>
          </li>
          <li class='one-warn-detail-info'>
            <ul class='list-inline'>
              <li class='one-light-text'>站点详细位置</li>
              <li style="width: 160px;vertical-align: top;">${dataObj.address}</li>
            </ul>
          </li>
          <li class='one-warn-detail-info'>
            <ul class='list-inline'>
              <li class='one-light-text'>监测次数</li>
              <li>${dataObj.coun}</li>
              <li><button class='btn btn-success' style='color: #fff;'>查看更多</button></li>
            </ul>
          </li>
        </ul>
      </div>
     </div>`
  };
  /*
   * 站点标注
   */
  mapLabel(dataObj) {
    const point = new BMap.Point(dataObj.longitude, dataObj.latitude);
    let size, offset, labelNameHtml, img;
    size = [30, 34];
    offset =  new BMap.Size(-size[0] / 2, -size[1] + 6);
    labelNameHtml = '<div class="one-site-label-name-right">' + dataObj.siteName + '</div>';
    if (dataObj.isNew === '1') {
      img = 'url(assets/v1/css/map/imgs/site-range-real.svg) no-repeat';
    } else {
      img = 'url(assets/v1/css/map/imgs/site-range-last.svg) no-repeat';
    }
    const myLabel = new BMap.Label(labelNameHtml,
      {
        offset: offset,
        position: point
      });
    myLabel.setStyle({
      maxWidth: size[0] + 'px',
      width: size[0] + 'px',
      display: 'inline-block',
      fontSize: '14px',
      border: '0',
      height: size[1] + 'px',
      textAlign: 'center',
      lineHeight: size[1] - 8 + 'px',
      background: img,
      backgroundSize: '100% 100%',
      cursor: 'pointer'
    });
    // const title = dataObj.siteName;
    // myLabel.setTitle(title);
    myLabel.setZIndex(-1);
    this.map.addOverlay(myLabel);
    myLabel.addEventListener( 'click', () => {
      this.openInfo(point, dataObj)
    })
  }

  /**
   * 打开弹窗
   * @param point
   * @param dataObj
   */
  openInfo(point, dataObj) {
    const infoHtml = this.siteInfoHtml(dataObj);
    const infoBox = new BMapLib.InfoBox(this.map, infoHtml, {
      boxStyle: {
        background: '#fff',
        width: '300px'
      },
      offset :  new BMap.Size(18, 28),
      boxClass: 'one-info-not-close',
      enableAutoPan: true,
      align: INFOBOX_AT_TOP,
      closeIconMargin: '9px 7px 0 0',
      closeIconUrl: 'assets/v1/css/map/imgs/ico-close.png'
    });
    if (this.lastInfo) {
      this.lastInfo.close();
    }
    this.lastInfo = infoBox;
    infoBox.open(point);
    $('.one-monitor-info-body .btn').click(() => {
      console.log('click');
      this.jumpToTable(dataObj.siteCode);
    })
  }
  changeShowName = (data) => {
    if (data) {
      $('.one-site-label-name-right').show();
    } else {
      $('.one-site-label-name-right').hide();
    }
  }
  /**
   * 跳转至表格页面
   */
  jumpToTable = (siteCode) => {
    this.router.navigate([RoutConstants.siteRangeTable, {siteCode: siteCode}], {relativeTo: this.route});
  };

  getSiteRangeInfo() {
    this.siteRangeMapService.getSiteRangeInfo().subscribe(
      result => this.responseUtil.success(result, () => {
          if (result && result.code === MsgConstants.MSG_CODE_OK) {
            if (result.data && result.data.length > 0) {
              result.data.forEach((val, i) => {
                if (i === result.data.length) {
                  console.log('aa');
                  this.map.centerAndZoom( new BMap.Point(val.longitude, val.latitude));
                }
                this.mapLabel(val)
              })
            }
          } else {
            this.dialogService.info(result.message)
          }
      }),
      error => this.responseUtil.error(error)
    )
  }
}
